package com.example.test.nettytest.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MessageDecoder extends ByteToMessageDecoder {
	private static Logger log = LoggerFactory.getLogger(MessageDecoder.class);
	private final int WRITE_SIZE = 8;

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) {
		try {
			in.discardReadBytes();
			in.markReaderIndex();
			int index = in.readerIndex();

			byte[] decoded = new byte[in.readableBytes()];
			in.readBytes(decoded);
			log.error("|" + ctx.channel().remoteAddress()
					+ "|Accept|" + CRC16M.getBufHexStr(decoded));

		} catch (Exception e) {
			e.printStackTrace();
			ctx.close();
			log.error("|" + ctx.channel().remoteAddress()
					+ "|decode error  ");
		}

	}

	public void printType(int type, ChannelHandlerContext ctx) {
		if (type == 3) {
			// logger.info(CTool.getnowtime() + "|"
			// + ctx.channel().remoteAddress()
			// + "|get comsu data  msg  back ");

		} else if (type == 51) {
			// logger.info(CTool.getnowtime() + "|"
			// + ctx.channel().remoteAddress()
			// + "|get addrlist msg  back ");
		}

		else if (type == 6) {
			// logger.info(ctx.channel().remoteAddress()
			// + " write msg back");

		} else if (type == 16) {

			// logger.info(CTool.getnowtime() + "|"
			// + ctx.channel().remoteAddress()
			// + "|update dac addrlist msg back ");
		} else {
			log.error(ctx.channel().remoteAddress() + " error type ：" + type);
			ctx.close();

		}

	}

}